package cmlabs.moduloariphmetics;

/**
 * Created by IntelliJ IDEA.
 * User: jte
 * Date: 14.4.11
 * Time: 22.55
 * To change this template use File | Settings | File Templates.
 */
public class UsualField implements Field {

    public UsualField(int m){
        this.m = m;
    }
    public int reverseElement(int a) {
        if (a == 0 || cmlabs.numbertheoryutils.Functions.gcd(a, m) != 1){
            throw new IllegalArgumentException();
        }
        return (int)cmlabs.numbertheoryutils.Functions.powMod(a, cmlabs.numbertheoryutils.Functions.phi(m) - 1, m);
    }

    public int add(int a, int b) {
        return (a % m + b % m) % m;
    }

    public int multiply(int a, int b) {
        return (a % m * b % m) % m;
    }

    public int divide(int a, int b) {
        if (b == 0 || cmlabs.numbertheoryutils.Functions.gcd(b, m) != 1){
            throw new IllegalArgumentException();
        }
        return (int)cmlabs.numbertheoryutils.Functions.powMod(a, reverseElement(b), m);
    }

    public int subtract(int a, int b) {
        return (a % m + m - b % m) % m;
    }

    private int m;
}
